package com.yfbao.horizon.demo;

import com.yfbao.horizon.utils.ConcurrentUtilsTest;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentLockTest {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(200);
        String key = "locke";
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            executorService.submit(() -> {
                long start = System.currentTimeMillis();
                boolean lock = ConcurrentUtilsTest.tryLock(key, 200);
                String name = Thread.currentThread().getName();
                ConcurrentUtilsTest.LockDto lock1 = ConcurrentUtilsTest.getLock(key);
                if (lock) {
                    if(lock1.isInCache()){
                        System.out.println(name +"---"+finalI+"-" + " locked success, get cache");
                    }else {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(name+"---"+finalI+"-" + " lockedSuccess");
                    }

                } else {

                    if(lock1.isInCache()){
                        System.out.println(name +"---"+finalI+"-" + " lockedfailed, get cache");
                    }else {
                        System.out.println(name +"---"+finalI+"-" + " lockedfailed, no cache--------------------------");
                    }

                }
                if (lock) {
                    try {
                        ConcurrentUtilsTest.releaseLockAndNotifyAll(key);
                        System.out.println(name + "---"+finalI+"-" +" locked release");
                    } catch (Exception e) {
                        System.out.println(name+"---"+finalI+"-" +":release error:" + e.getMessage());
                    }
                }
                countDownLatch.countDown();
                System.out.println(name+"---"+finalI+"-" +"  total cost:"+(System.currentTimeMillis()-start));
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("finished all");
    }

}
